package clt.com.filter;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebFilter(filterName="firstFilter", urlPatterns = {
        "/*"
        })
public class FirsrtFilter implements Filter{
	//private static Logger LOG = LoggerFactory.getLogger(FirsrtFilter.class);
	
	// 白名单
	private List<String> whiteUrls;
		
	private int w_size = 0;
	@Override
    public void init(FilterConfig filterConfig) throws ServletException {
		// 读取文件
		whiteUrls = readFile(FirsrtFilter.class.getResource("/csrfWhite.txt").getPath());
		w_size=null==whiteUrls?0:whiteUrls.size();
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        //String requestURI = req.getRequestURI();
        //LOG.info("过滤到的请求--->"+requestURI);
		HttpServletResponse rep = (HttpServletResponse) response;

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        String token = req.getHeader("token");//header方式
        
        boolean isFilter = false;

        String method = ((HttpServletRequest) request).getMethod();
        // 获取请求url地址
		String url = req.getRequestURL().toString();
		String referurl = req.getHeader("Referer");
		String str = url.substring(url.lastIndexOf(".")+1);
		/*if("html".equals(str) && !"css".equals(str) && !"gif".equals(str) && !"jpg".equals(str) && !"ico".equals(str)){
			if (url.endsWith("login.html") || url.endsWith("index.html") || url.endsWith("homePage.html")
					|| url.endsWith("cltweb/page/index.html") || isWhiteReq(referurl)) {
				chain.doFilter(request, response);
			} else {
				rep.sendRedirect(req.getContextPath() + "/login.html");
				return;
			}
		}else{
		}*/
		chain.doFilter(request, response);
		//LOG.info("url:" + url + "\t referurl----->", referurl);		
    }
    /*
	 * 判断是否是白名单
	 */
	private boolean isWhiteReq(String referUrlp) {
		//LOG.info("isWhiteReq", "w_size="+w_size);
		if (referUrlp == null || "".equals(referUrlp)||w_size==0) {
			return false;
		} else {
			String refHost = "";
			String referUrl = referUrlp.toLowerCase();
			if (referUrl.startsWith("http://")) {
				refHost = referUrl.substring(7);
			} else if (referUrl.startsWith("https://")) {
				refHost = referUrl.substring(8);
			}
			
			for (String urlTemp : whiteUrls) {
				if (refHost.indexOf(urlTemp.toLowerCase()) > -1) {
					return true;
				}
			}
		}

		return false;
	}
    @Override
    public void destroy() {

    }
    private List<String> readFile(String fileName){
		List<String> list = new ArrayList<>();
		InputStreamReader read = null;
		BufferedReader reader = null;
		FileInputStream fs = null;
		try {
			File f = new File(fileName);
			if(f.isFile() && f.exists()){
				fs = new FileInputStream(f);
				read = new InputStreamReader(fs, "UTF-8");
				reader = new BufferedReader(read);
				String line;
				while((line=reader.readLine()) != null){
					if(!"".equals(line)){						
						list.add(line);
					}
				}
			}
		} catch (Exception e) {
			//LOG.error("updateSnsServAcctStat", "批量记录操作日志失败!", e);
		}finally {
			try {
				if(fs != null){
					fs.close();
				}
				if(read != null){
					read.close();
				}
				if(reader != null){
					reader.close();
				}
			} catch (IOException e) {
				//LOG.error("", "",e);
			}
		}
		return list;
	}
}
